package com.miyu.common.utils.filter.result;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * 结果返回处理
 *
 * @author MIYU
 * @date 2022/06/03
 */
@RestControllerAdvice
public class ResultUtils implements ResponseBodyAdvice<Object> {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(body instanceof ComResultPJ){
            return body;
        }else
        if(body==null){
            return ComResult.error("ERROR");
        }else if(body instanceof String){
           /* String属于特殊情况，需要单独处理，否则会报错*/
            try {
                return objectMapper.writeValueAsString(ComResult.success(body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                ComResult.error("ERROR");
           }
        }
        return ComResult.success(body);
    }




}
